package com.learning.platform.repository;

import com.learning.platform.entity.UserLearningContext;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 用户学习上下文数据访问接口
 */
@Repository
public interface UserLearningContextRepository extends JpaRepository<UserLearningContext, Long> {
    
    /**
     * 根据用户ID查找学习上下文
     */
    Optional<UserLearningContext> findByUserId(Long userId);
    
    /**
     * 查找活跃用户的学习上下文
     */
    @Query("SELECT ulc FROM UserLearningContext ulc WHERE ulc.lastActiveAt >= :since ORDER BY ulc.lastActiveAt DESC")
    List<UserLearningContext> findActiveContexts(@Param("since") LocalDateTime since);
    
    /**
     * 根据编程语言查找用户上下文
     */
    List<UserLearningContext> findByCurrentLanguage(String language);
    
    /**
     * 根据技能水平查找用户上下文
     */
    List<UserLearningContext> findBySkillLevel(String skillLevel);
    
    /**
     * 查找最近更新的上下文
     */
    List<UserLearningContext> findTop10ByOrderByUpdatedAtDesc();
    
    /**
     * 统计用户总提问数
     */
    @Query("SELECT SUM(ulc.totalQuestionsAsked) FROM UserLearningContext ulc")
    Long getTotalQuestionsCount();
    
    /**
     * 统计编程相关提问数
     */
    @Query("SELECT SUM(ulc.programmingQuestionsAsked) FROM UserLearningContext ulc")
    Long getProgrammingQuestionsCount();
    
    /**
     * 查找特定时间段内活跃的用户
     */
    @Query("SELECT COUNT(ulc) FROM UserLearningContext ulc WHERE ulc.lastActiveAt BETWEEN :start AND :end")
    Long countActiveUsersBetween(@Param("start") LocalDateTime start, @Param("end") LocalDateTime end);
}

